﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Reflection;
using AspectCore.Extensions.Reflection;
using netCoreStudy.Attr.QueryAttr;
using netCoreStudy.Enum;

namespace netCoreStudy.Express
{
	/// <summary>
	/// orderBy  IQueryable 扩展
	/// </summary>
	public static class OrderByExt
	{

		public static IQueryable<TSource> OrderByExp<TSource, T>(
			this IQueryable<TSource> queryList, T queryEntity)
		{
			Type typeSource = typeof(TSource); // 数据源列表元素对象类型(Student,People)
			Type typeQuery = typeof(T);
			PropertyReflector[] queryReflectors = ReflectorDic.GetPropReflector(typeQuery);
			PropertyReflector[] sourceReflectors = ReflectorDic.GetPropReflector(typeSource);

			string orderByStr = "";
			foreach (PropertyReflector reflector in queryReflectors)
			{
				// 如果属性有orderBy特性 
				OrderByAttribute orderByAttr =
					reflector.GetCustomAttribute<OrderByAttribute>();
				if (orderByAttr == null) continue;
				// 获取 属性 的值  QueryParameter.OrderBy="createTime"
				orderByStr = reflector.GetValue(queryEntity) as string;
				if (string.IsNullOrWhiteSpace(orderByStr))
				{
					throw new Exception(
						$"特性里orderBy{reflector.Name}这个属性名有问题!" +
						$"\n{typeSource.Name}的这个类里面 " +
						$" {reflector.Name} 是空的! ");
				}
			}

			string[] orderByStrs = orderByStr.Split(',');
			for (var i = 0; i < orderByStrs.Length; i++)
			{
				string orderStrUnit = orderByStrs[i];
				bool b = sourceReflectors.Select(x => x.Name.ToLower())
					.Any(x => x == orderStrUnit.RemoveDesc().ToLower());
				if (!b)
					throw new Exception(
						$"排序字段有问题! \n{typeSource.Name}的这个类里面 " +
						$" 没有 {orderStrUnit.RemoveDesc()} 这个 字段！ ");
			}

			string newOrderByStr = orderByStr.Trim().Replace(" desc", " descending");

			return queryList.OrderBy(newOrderByStr);
		}
	}
}